package com.hxzf.mvp.commons.aspect;

import com.github.pagehelper.PageHelper;
import com.hxzf.mvp.commons.constant.SysConstant;
import com.hxzf.mvp.commons.domain.Pageable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 分页拦截器
 *
 * <p>只要存在pageNum、pageSize或者orderBy中任一参数就会启动分页插件
 *
 * @author Kai
 * @date 2021/12/16 17:29
 **/
@Slf4j
@Aspect
@Component
public class PagingAspect {

    @Around(value = "@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public Object aroundMethodWithParam(ProceedingJoinPoint pjd) throws Throwable {
        Object[] params = pjd.getArgs();

        if (ArrayUtils.isEmpty(params)) {
            return pjd.proceed();
        }

        for (Object param : params) {
            if (param instanceof Pageable) {
                Pageable paging = (Pageable) param;
                Integer num = paging.getPageNum();
                Integer size = paging.getPageSize(); // zero means no paging!
                String orderBy = paging.getOrderBy();
                if (num != null || size != null || orderBy != null) {
                    Integer numParam = ObjectUtils.defaultIfNull(num, SysConstant.DEFAULT_PAGE_NUM);
                    Integer sizeParam = ObjectUtils.defaultIfNull(size, SysConstant.DEFAULT_PAGE_SIZE);

                    // 阈值
                    if (numParam > SysConstant.MAX_PAGE_NUM) {
                        numParam = SysConstant.MAX_PAGE_NUM;
                    }
                    if (sizeParam > SysConstant.MAX_PAGE_SIZE) {
                        sizeParam = SysConstant.MAX_PAGE_SIZE;
                    }

                    // 启动分页排序插件
                    if (num == null && size == null && StringUtils.isNoneBlank(orderBy)) {
                        PageHelper.orderBy(orderBy);
                    } else if (StringUtils.isNoneBlank(orderBy)) {
                        PageHelper.startPage(numParam, sizeParam, orderBy);
                    } else {
                        PageHelper.startPage(numParam, sizeParam);
                    }
                }

                break;
            }
        }

        return pjd.proceed();
    }

}
